package com.sgb.kjwl.viewmodel.home;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.util.Pair;

import com.amap.api.services.geocoder.GeocodeAddress;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sgb.alimaplibrary.MapPoiTools;
import com.sgb.goods.view.activity.inquiry.InquiryPublishingActivity;
import com.sgb.kjwl.AppConstant;
import com.sgb.kjwl.api.APIManager;
import com.swgk.core.base.api.ICallBack;
import com.sgb.kjwl.api.service.MailListAPI;
import com.sgb.kjwl.model.entity.BannerEntity;
import com.swgk.core.view.entity.ChannelEntity;
import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.model.entity.MaterialMenuEntity;
import com.swgk.core.base.aroute.AppRouteConstant;
import com.swgk.core.common.utils.ActivityJump;
import com.swgk.core.util.MToast;
import com.swgk.core.view.entity.MenuEntity;
import com.sgb.kjwl.model.entity.ProvinceEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.businessmanagement.CompanyEntity;
import com.sgb.kjwl.model.entity.home.CityEntity;
import com.sgb.kjwl.model.entity.user.EssentiaIinformationeEntity;
import com.sgb.kjwl.repository.HomeRepertory;
import com.sgb.kjwl.service.LocationService;
import com.sgb.kjwl.utils.UserInfoCacheUtils;
import com.sgb.kjwl.view.event.ChooseAreaEvent;
import com.swgk.core.event.EventConstant;
import com.swgk.core.mmkvutil.CacheMarker;
import com.sgb.kjwl.view.ui.fragment.HomeFragment3;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.mmkvutil.DatalUtils;
import com.swgk.core.util.MLog;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Type;
import java.util.List;

import io.reactivex.functions.Consumer;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class HomeFragModel3 extends BaseViewModel {
    private HomeRepertory repertory;
    private HomeFragment3 fragment;

    public HomeFragModel3(HomeFragment3 fragment, HomeRepertory repertory) {
        this.fragment = fragment;
        this.repertory = repertory;
    }

    //原省级位置切换IP定位接口
    public void getLocalProvince() {
        APIManager.getInstance().getCommonAPI().getCurrentArea().enqueue(new ICallBack<BaseEntity<List<ProvinceEntity<List<ProvinceEntity>>>>>() {
            @Override
            public void onSuccess(BaseEntity<List<ProvinceEntity<List<ProvinceEntity>>>> data) {
                List<ProvinceEntity<List<ProvinceEntity>>> provinceEntityList = data.getData();
                for (ProvinceEntity<List<ProvinceEntity>> provinceEntity : provinceEntityList) {
                    if (provinceEntity.isChecked() == true) {
                        Log.d("选中的城市", provinceEntity.getAreaName());
                        if (provinceEntity != null) {
                            repertory.setLocalCode(String.valueOf(provinceEntity.getId()));
                            if (Integer.parseInt(repertory.getAreaCode()) != provinceEntity.getId()) {

                                fragment.showChangeDialog(provinceEntity);
                            }
                        }
                        return;
                    }
                }
            }
        });
    }

    /**
     * 获取当前IP定位城市信息
     */
    public void getLocalCity() {
        APIManager.getInstance().getCommonAPI().getCurrentCity().enqueue(new ICallBack<BaseEntity<CityEntity>>() {
            @Override
            public void onSuccess(BaseEntity<CityEntity> data) {
                if (!repertory.getAreaCode().equals(data.getData().getCityCode())) {
                    fragment.showChangeDialog(data.getData());
                }
            }
        });
    }

    public void saveProvinceModel(ProvinceEntity<List<ProvinceEntity>> list) {
        MapPoiTools.newInstance(fragment.getContext(), null, new MapPoiTools.CalllBack() {
            @Override
            public void onRegeocodeSearched(GeocodeAddress geocodeAddress) {
                getAreaNameModel(geocodeAddress, list);
            }
        }).addressSearchQuery(list.getAreaName().trim(), "");
    }

    private void getAreaNameModel(GeocodeAddress geocodeAddress, ProvinceEntity<List<ProvinceEntity>> list) {
        String cityName = list.getAreaName();
        if (cityName.contains("市")) {
            cityName = cityName.substring(0, cityName.length() - 1);
        }
        double latitude = geocodeAddress.getLatLonPoint().getLatitude();//纬度
        double longititude = geocodeAddress.getLatLonPoint().getLongitude();//经度
        String adcode = geocodeAddress.getAdcode();//区域编码
        repertory.setAreaCode(String.valueOf(list.getId()));
        repertory.setAreaName(cityName);
        repertory.setLatitude(String.valueOf(latitude));
        repertory.setLongititude(String.valueOf(longititude));
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.SelectLONGITUDE, longititude + "");
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.SelectLATITUDE, latitude + "");
        SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.AREA_CODE, repertory.getAreaCode());
        SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.AREA_NAME, repertory.getAreaName());
        EventBus.getDefault().postSticky(ChooseAreaEvent.make(EventConstant.EVENT_CHOOSE_AERA, list));
        fragment.showAreaName(cityName);
        MLog.e("高德当前选中地理编码", adcode);
        MLog.e("高德当前选中 纬度latitude", latitude + "");
        MLog.e("高德当前选中 经度longititude", longititude + "");
        MLog.e("接口返回 地理编码", list.getId() + "");
        MLog.e("接口返回 城市名称", cityName + "");
    }

    public String getCityName() {
        return repertory.getAreaName();
    }

    //首页banner
    @SuppressLint("CheckResult")
    public void getBannerModel() {
        repertory.getHomeBanner()
                .subscribe(new Consumer<BaseEntity<List<BannerEntity>>>() {
                    @Override
                    public void accept(BaseEntity<List<BannerEntity>> listBaseEntity) throws Exception {
                        if (listBaseEntity.getState().equals(AppConstant.REQEUST_SECCUESS)) {
//                            fragment.showBannerView(listBaseEntity.getData());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        MLog.d(AppConstant.API_LOG, throwable.getMessage());
                    }
                });
    }

    //首页menu
    @SuppressLint("CheckResult")
    public void getMenuModel() {
        repertory.getHomeMenu()
                .subscribe(new Consumer<BaseEntity<List<MenuEntity>>>() {
                    @Override
                    public void accept(BaseEntity<List<MenuEntity>> listBaseEntity) throws Exception {
                        if (listBaseEntity.getState().equals(AppConstant.REQEUST_SECCUESS)) {
//                            fragment.showMenuView(listBaseEntity.getData());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        MLog.d(AppConstant.API_LOG, throwable.getMessage());
                    }
                });
    }

    //首页推荐列表
    @SuppressLint("CheckResult")
    public void getRecommendListModel() {
        repertory.getHomeRecommendType(repertory.getAreaCode())
                .subscribe(new Consumer<BaseEntity<List<MaterialMenuEntity>>>() {
                    @Override
                    public void accept(BaseEntity<List<MaterialMenuEntity>> listBaseEntity) throws Exception {
                        if (listBaseEntity.getState().equals(AppConstant.REQEUST_SECCUESS)) {
//                            fragment.showRecommendList(listBaseEntity.getData());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        MLog.d(AppConstant.API_LOG, throwable.getMessage());
                    }
                });
    }

    /**
     * 获取当前经纬度
     */
    public void getLocation() {
        SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.LONGITUDE_ID, "");
        SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.LATITUDE_ID, "");
        if (CheckUtils.isServiceRunning(fragment.getActivity(), "com.sgb.kjwl.service.LocationService")) {
            Intent intent = new Intent(fragment.getActivity(), LocationService.class);
            if (fragment != null && fragment.isAdded()) {
                fragment.requireActivity().stopService(intent);
            }
        }
        Intent intent = new Intent(fragment.getActivity(), LocationService.class);
        intent.putExtra("isFreightTransport", false);
        if (fragment != null && fragment.isAdded()) {
            //   fragment.requireActivity().startService(intent);
            fragment.getActivity().startService(intent);
        }
    }

    //获取title
    public void getChannelList() {
      /*  Type type = new TypeToken<List<ChannelEntity>>() {
        }.getType();
        Object object = DatalUtils.getInstance().getData(MkvUtils.CommomData, CacheMarker.LocalHomePageTitle, type);
        if (object != null){
            fragment.getChannel((List<ChannelEntity>) object);
            return;
        }*/
        APIManager.getInstance().getCommonAPI().getChannelList().enqueue(new ICallBack<BaseEntity<List<ChannelEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<ChannelEntity>> data) {
                String caCheDataString = DatalUtils.getHashData(MkvUtils.CommomData, CacheMarker.SysHomePageTitle);
                String caCheDataHas = DatalUtils.getInstance().strToHashKey(data.getData());
                Type type = new TypeToken<List<ChannelEntity>>() {
                }.getType();
                Object object = DatalUtils.getInstance().getData(MkvUtils.CommomData, CacheMarker.LocalHomePageTitle, type);
                //当缓存数据的hash值和返回数据的hash值不一致时，或者 缓存数据为空时，重新刷新初始化数据集合
                if (null == object || !caCheDataHas.equals(caCheDataString)) {
                    DatalUtils.getInstance().putData(MkvUtils.CommomData, CacheMarker.LocalHomePageTitle, data.getData());
                    DatalUtils.getInstance().putData(MkvUtils.CommomData, CacheMarker.SysHomePageTitle, data.getData());
                    //fragment.getChannel(data.getData());
                    fragment.showChannelChangeDialog();
                } else {
                    fragment.getChannel((List<ChannelEntity>) object);
                }
            }


            @Override
            public void onFailure(Call<BaseEntity<List<ChannelEntity>>> call, Throwable t) {
                super.onFailure(call, t);
                Type type = new TypeToken<List<ChannelEntity>>() {
                }.getType();
                Object object = DatalUtils.getInstance().getData(MkvUtils.CommomData, CacheMarker.LocalHomePageTitle, type);
                //当缓存数据的hash值和返回数据的hash值不一致时，或者 缓存数据为空时，重新刷新初始化数据集合
                if (null != object) {
                    fragment.getChannel((List<ChannelEntity>) object);
                } else {
                    if (t != null && !TextUtils.isEmpty(t.getMessage()) &&
                            (t.getMessage().contains("请重新登录") || t.getMessage().contains("不允许访问"))) {
                        getChannelList();
                    }
                }
            }
        });
    }

    public String getToken() {
        return repertory.getToken();
    }

    public void getUserInfo() {
        APIManager.getInstance().getUserAPI().getUserInfo().enqueue(new Callback<BaseEntity<UserMsgEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<UserMsgEntity>> call, Response<BaseEntity<UserMsgEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getData() == null) return;
                if (response.body().getState().equals("ok")) {
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.USER_NAME, response.body().getData().getUsername());
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.USER_NO, response.body().getData().getNo());
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.REAL_NAME, response.body().getData().getRealName());
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.DRIVER_AUTH, response.body().getData().isDriverAuth() ? "SUCCESS" : "NONE");
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.ENTERPRISE_AUTH, response.body().getData().isRelevance() ? "SUCCESS" : "NONE");
                    /*if (response.body().getData().getEnterprise() == null)
                        return;
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.COMPANY_NAME,response.body().getData().getEnterprise().getCompanyName() );
                    Log.e("公司no",response.body().getData().getEnterprise().getNo());
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.REAL_ID, response.body().getData().getEnterprise().getId());*/

                }
            }

            @Override
            public void onFailure(Call<BaseEntity<UserMsgEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });

    }

    /**
     * 公司列表信息
     */
    public void getCompanyList() {
        DialogHelper.showProgressDialog(fragment.getContext(), "请求中...").setCanceledOnTouchOutside(false);
        APIManager.getInstance().getMailListAPI().getUserCompany(MailListAPI.UserCenterUrl.URL_GET_USER_COMPANY).enqueue(new Callback<BaseEntity<List<CompanyEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<CompanyEntity>>> call, Response<BaseEntity<List<CompanyEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if (response.body().getState().equals("ok")) {
                    fragment.showCompanyList(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<CompanyEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    /**
     * 设置主企业
     *
     * @param companyEntity
     */
    public void settingMainCompany(CompanyEntity companyEntity) {
        if (!DialogHelper.isShowing()) {
            DialogHelper.showProgressDialog(fragment.getContext(), "请求中...").setCanceledOnTouchOutside(false);
        }
        APIManager.getInstance().getMailListAPI().settingMainCompany(companyEntity.getCompNo(), companyEntity.getType()).enqueue(new Callback<BaseEntity<LoginEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<LoginEntity>> call, Response<BaseEntity<LoginEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if (response.body().getState() == null) return;
                if (response.body().getState().equals("ok")) {
                    // 保存 token
                    LoginEntity entity = response.body().getData();
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.resourcePCToken, entity.getResourcePCToken());
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.resourceAPPToken, entity.getResourceAPPToken());
                    //给SharedPreferenceUtil中的COMPANY_NO赋值 保存公司ID
                    Log.e("公司no", companyEntity.getCompNo());
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.COMPANY_NO, companyEntity.getCompNo());
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.ENTERPRISE_NO, companyEntity.getCompNo());
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.COMPANY_NAME, companyEntity.getCompName());
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.COMP_LOGO, companyEntity.getCompLogo());
                    //查询个人中心商品列表
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.REAL_ID, companyEntity.getCompanyId());
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.COM_TYPE, companyEntity.getType());
                    repertory.saveToken(entity.getToken());
                    fragment.setCurrentCompany(companyEntity);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<LoginEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }


    /**
     * 获取用户的基本信息
     */
    public void getEssentialInformation(CompanyEntity companyEntity) {
        if (!DialogHelper.isShowing()) {
            DialogHelper.showProgressDialog(fragment.getContext(), "请求中...").setCanceledOnTouchOutside(false);
        }
        APIManager.getInstance().getUserAPI().getEssential_information(companyEntity.getCompNo(), String.valueOf(companyEntity.getType())).enqueue(new Callback<BaseEntity<EssentiaIinformationeEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<EssentiaIinformationeEntity>> call, Response<BaseEntity<EssentiaIinformationeEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getData() != null) {
                    String CacheMateialistlHash = DatalUtils.getHashData(MkvUtils.get().CommomData, CacheMarker.CacheUserInfo);
                    Gson gson = new Gson();
                    //获取从网络请求下来的数据的哈希值
                    String data1 = gson.toJson(response.body().getData());
                    String mHashNet = DatalUtils.strToHashKey(data1);
                    if (!CacheMateialistlHash.equals(mHashNet)) {
                        //存储用户的基本信息
                        UserInfoCacheUtils.setUserInfoData(response.body().getData());
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<EssentiaIinformationeEntity>> call, Throwable t) {
            }
        });
    }

    /*
     * 获取当前默认选中的城市
     * */
    public String getCurrentLocal() {
        String name;
        if (repertory.getAreaName().length() >= 3) {
            name = repertory.getAreaName().substring(0, 2);
        } else {
            name = repertory.getAreaName();
        }

        SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.AREA_CODE, repertory.getAreaCode());
        SharedPreferenceUtil.getInstance().saveString(SharedPreferenceUtil.AREA_NAME, repertory.getAreaName());
        return name;
    }

    //1.5.7 商品首页询价新增token失效的校验，后端提议用这个接口来判断
    public void getUserInfoCheck() {
        DialogHelper.showProgressDialog(fragment.getActivity(), null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().getUserInfo().enqueue(new Callback<BaseEntity<UserMsgEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<UserMsgEntity>> call, Response<BaseEntity<UserMsgEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if (response.body().getState().equals("ok")) {
                    if (response.body().getData() == null) return;
                    Intent createGoods = new Intent(fragment.getActivity(), InquiryPublishingActivity.class);
                    fragment.getActivity().startActivity(createGoods);
                } else {
                    MToast.showToast(fragment.getActivity(), "登录过期,请重新登录");
                    ActivityJump.startActivity(AppRouteConstant.VerificationCodeLoginActivity, Pair.create("isJump", false));
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<UserMsgEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }
}
